//注册拦截器

package com.c4.config;

import com.c4.interceptors.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //接口不拦截
//        registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login","/user/register","/sort","/mecha","/mecha/findBySortId");
        registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login","/user/register","/ai/chat");
    }

    /*  // 尝试注释掉这个方法
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:5176") // 你的前端地址
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
    */

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:5173"); // 确保这里的端口号与前端应用的实际端口号一致 (之前是5174，错误信息中是5173)
        config.addAllowedOrigin("http://localhost:5176"); // 同时允许5174，以防万一
        config.addAllowedMethod("*"); // 允许所有请求方法，可细化
        config.addAllowedHeader("*"); // 允许所有请求头，可细化
        config.setAllowCredentials(true); // 明确设置允许凭证
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
